<template>
  <el-dialog
    top="80px"
    :visible.sync="isVisible"
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-container>
      <el-main
        v-loading="submitLoading"
        :style="{ 'max-height': maxHeightDialog }"
        :element-loading-text="submitLoading ? '提交中...' : '加载中...'"
        class="container-main"
      >
        <div>
          <div class="title">
            <span>填写信息</span>
          </div>

          <el-card
            class="card"
            shadow="never"
            style="background: #fafafa; min-height: 450px"
          >
            <div style="margin-left: -12px; margin-right: -12px">
              <el-row>
                <el-col :span="13">
                  <el-form
                    ref="elForm"
                    size="small"
                    label-position="right"
                    :model="form"
                    :rules="rules"
                    label-width="25%"
                  >
                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="上级网格">
                          <treeselect
                            v-model="form.parentGuid"
                            placeholder="选择上级网格"
                            :options="gridTreeDataList"
                            :default-expand-level="Infinity"
                            style="width: 100%"
                            @select="onParentGridSelect"
                          >
                            <div slot="value-label" slot-scope="{ node }">
                              {{ node.raw.fullPathText }}
                            </div>
                          </treeselect>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="网格名称" prop="name">
                          <el-input
                            v-model="form.name"
                            placeholder="请输入网格名称"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="所属部门" prop="deptGuid">
                          <treeselect
                            v-model="form.deptGuid"
                            placeholder="选择所属部门"
                            :options="deptTreeDataList"
                            :default-expand-level="Infinity"
                            style="width: 100%"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="所属省">
                          <el-select
                            v-model="form.province"
                            placeholder="请选择所属省"
                            filterable
                            clearable
                            style="width: 100%"
                            @change="getCityList(true)"
                          >
                            <el-option
                              v-for="item of provinceList"
                              :key="item.codeId"
                              :label="item.positionName"
                              :value="item.positionName"
                            /> </el-select
                        ></el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="所属地市">
                          <el-select
                            v-model="form.city"
                            placeholder="请选择地市"
                            filterable
                            clearable
                            style="width: 100%"
                            @change="getCountyList(true)"
                          >
                            <el-option
                              v-for="item of cityList"
                              :key="item.codeId"
                              :label="item.positionName"
                              :value="item.positionName"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="所属区县">
                          <el-select
                            v-model="form.county"
                            placeholder="请选择区县"
                            filterable
                            clearable
                            style="width: 100%"
                          >
                            <el-option
                              v-for="item of countyList"
                              :key="item.codeId"
                              :label="item.positionName"
                              :value="item.positionName"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="经度" prop="longitude">
                          <el-input
                            v-model="form.longitude"
                            placeholder="请输入经度"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="纬度" prop="latitude">
                          <el-input
                            v-model="form.latitude"
                            placeholder="请输入纬度"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="排序">
                          <el-input-number v-model="form.orderNum" />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="上传网格2D平面图">
                          <el-upload
                            :action="uploadUrl"
                            :headers="{ Authorization: token }"
                            list-type="picture-card"
                            :show-file-list="false"
                            :on-success="handleSuccess"
                            :on-error="handleImgError"
                            :disabled="planImgUrl != ''"
                          >
                            <img
                              v-if="planImgUrl != ''"
                              :src="planImgUrl"
                              style="
                                width: 146px;
                                height: 146px;
                                display: block;
                              "
                            />

                            <div
                              style="
                                background-color: rgba(0, 0, 0, 0.45);
                                width: 16px;
                                height: 16px;
                                position: absolute;
                                top: 2px;
                                left: 130px;
                              "
                              v-if="planImgUrl != ''"
                            >
                              <el-popconfirm
                                title="确定要删除该平面图吗？"
                                @confirm="onConfirmDelete"
                              >
                                <i
                                  class="el-icon-close"
                                  style="
                                    position: absolute;
                                    top: 2px;
                                    right: 0px;
                                    font-size: 14px;
                                    color: white;
                                  "
                                  slot="reference"
                                ></i>
                              </el-popconfirm>
                            </div>
                            <i
                              v-if="planImgUrl == ''"
                              class="el-icon-plus avatar-uploader-icon"
                            ></i>
                          </el-upload>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </el-col>

                <el-col :span="11">
                  <div style="margin: 0 10px">
                    <grid-map
                      :longitude="String(form.longitude)"
                      :latitude="String(form.latitude)"
                      :is-click-get-lng-lat="isClickGetLngLat"
                      @getPoint="toGetPoint"
                    />
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </div>
      </el-main>

      <el-footer>
        <el-button
          size="medium"
          icon="el-icon-close"
          :disabled="submitLoading"
          style="width: 120px; margin-right: 10px"
          @click="isVisible = false"
        >
          取消
        </el-button>
        <el-button
          size="medium"
          type="primary"
          icon="el-icon-check"
          :disabled="submitLoading"
          :loading="submitLoading"
          style="width: 120px"
          @click="toSubmit"
        >
          {{ params.type == 'edit' ? '修改' : '提交' }}
        </el-button>
      </el-footer>
    </el-container>
  </el-dialog>
</template>

<script>
import dataFormMixins from '@/mixins/data-form-mixins'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import GridManageApi from '@/api/grid-manage'
import GridMap from './Map'
import { getToken } from '@/utils/auth'

export default {
  name: 'GridAdd',
  components: {
    Treeselect,
    GridMap,
  },
  mixins: [dataFormMixins],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    params: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      deptTreeDataList: [],
      deptTreeLoading: false,
      gridTreeDataList: [],

      provinceList: [],
      cityList: [],
      countyList: [],

      isClickGetLngLat: false,

      uploadUrl:
        process.env.VUE_APP_BASE_API +
        'system/files/uploadFolder?FolderName=GridFile',
      token: 'bearer ' + getToken(),
      uploadFile: {},
      planImgUrl: '',
      imageId: '',
      imgDialogVisible: false,
      imageId1: '',
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.dialogVisible
      },
      set() {
        this.toClose()
      },
    },
  },
  mounted() {
    this.rules = this.initRules()
    this.form = this.initForm()

    this.getGridTreeDataList()
    this.getDeptTreeDataList()

    if (this.params.type === 'add' || this.params.type === 'edit') {
      this.getGridAll(this.params.item.guid, true)
      if (this.params.type === 'edit') {
        this.getImg()
      }
    } else {
      this.getProvinceList()
    }
  },
  methods: {
    initRules() {
      return {
        name: this.getValidatorForm(),
        deptGuid: this.getValidatorForm('change'),
        longitude: this.getValidatorForm(),
        latitude: this.getValidatorForm(),
      }
    },
    initForm() {
      return {
        guid: '',
        parentGuid: null, // 上级网格
        name: '', // 网格名称
        deptGuid: null, // 所属部门
        longitude: null, // 经度
        latitude: null, // 纬度
        province: '', // 所属省
        city: '', // 所属市
        county: '', // 所属区县
        // orderNum: 0, // 排序
        zoonId: '', // 区域编码
      }
    },

    getGridTreeDataList() {
      GridManageApi.getGridTree()
        .then((ret) => {
          this.gridTreeDataList = ret.data.data.rows
        })
        .catch(() => {
          this.gridTreeDataList = []
        })
    },
    getDeptTreeDataList() {
      // this.deptTreeLoading = true
      GridManageApi.getDeptTree()
        .then((ret) => {
          this.deptTreeDataList = ret.data.data.rows
          this.deptTreeDataList.forEach((ele) => {
            this.getDeptGuidTree(ele)
          })
          this.deptTreeLoading = false
          console.log('deptTreeDataList=', this.deptTreeDataList)
        })
        .catch(() => {
          this.deptTreeLoading = false
          this.deptTreeDataList = []
        })
    },
    getDeptGuidTree(ele) {
      ele.id = ele.guid
      if (ele.children) {
        ele.children.forEach((chilEle) => {
          this.getDeptGuidTree(chilEle)
        })
      }
    },

    getGridAll(guid, bool) {
      const data = {
        guid: guid,
      }
      GridManageApi.getGridAll(data).then((ret) => {
        const list = ret.data.data
        if (bool) {
          if (this.params.type === 'add') {
            this.form.parentGuid = list[0].guid
            this.form.province = list[0].province
            this.form.city = list[0].city
            this.form.county = list[0].county
            this.form.longitude = list[0].longitude
            this.form.latitude = list[0].latitude
          } else if (this.params.type === 'edit') {
            this.form = { ...list[0] }

            // this.form.createTime = new Date(new Date(this.form.createTime))
          }
        } else {
          this.form.province = list[0].province
          this.form.city = list[0].city
          this.form.county = list[0].county
          this.form.longitude = list[0].longitude
          this.form.latitude = list[0].latitude
        }

        this.getProvinceList()
      })
    },
    onParentGridSelect(node) {
      this.getGridAll(node.guid, false)
    },

    getProvinceList() {
      const data = {
        label: 'level',
        value: 1,
      }
      GridManageApi.getPositionList(data).then((ret) => {
        this.provinceList = ret.data.data

        // if (this.params.type === 'add' || this.params.type === 'edit') {
        //   if (this.form.province && this.form.province !== '') {
        //     this.getCityList(false)
        //   }
        // }

        if (this.form.province && this.form.province !== '') {
          this.getCityList(false)
        }
      })
    },
    getCityList(bool) {
      if (bool) {
        this.cityList = []
        this.countyList = []
        this.form.city = ''
        this.form.county = ''
      }
      const data = {
        label: 'parentCodeId',
        value: '',
      }

      this.provinceList.forEach((ele) => {
        if (ele.positionName === this.form.province) {
          data.value = ele.codeId
        }
      })
      GridManageApi.getPositionList(data).then((ret) => {
        this.cityList = ret.data.data

        // if (this.params.type === 'add' || this.params.type === 'edit') {
        //   if (this.form.city && this.form.city !== '') {
        //     this.getCountyList(false)
        //   }
        // }

        if (this.form.city && this.form.city !== '') {
          this.getCountyList(false)
        }
      })
    },
    getCountyList(bool) {
      if (bool) {
        this.countyList = []
        this.form.county = ''
      }

      const data = {
        label: 'parentCodeId',
        value: '',
      }
      this.cityList.forEach((ele) => {
        if (ele.positionName === this.form.city) {
          data.value = ele.codeId
        }
      })
      GridManageApi.getPositionList(data).then((ret) => {
        this.countyList = ret.data.data
      })
    },

    toGetPoint(data) {
      console.log('data', data)
      this.form.longitude = data.lng
      this.form.latitude = data.lat
      this.isClickGetLngLat = true
    },

    toClose() {
      this.$emit('close')
    },
    toSubmit() {
      this.$refs.elForm.validate((valid) => {
        console.log('form', this.form)
        if (valid) {
          const model = this.formatFormData(this.form)
          // const model = {}
          // for (const key in this.form) {
          //   model[key] = this.form[key]
          // }
          model.province = this.getCodeId(this.provinceList, 'province')
          model.city = this.getCodeId(this.cityList, 'city')
          model.county = this.getCodeId(this.countyList, 'county')
          if (model.county) {
            model.zoonId = model.county
          } else if (model.city) {
            model.zoonId = model.city
          } else if (model.province) {
            model.zoonId = model.province
          }
          model.imageId = this.imageId
          console.log('model=', model)
          this.submitLoading = true
          if (this.params.type === 'add' || this.params.type === 'addEmpty') {
            GridManageApi.addGrid(model)
              .then((ret) => {
                this.submitLoading = false
                this.isVisible = false
                this.$message({
                  message: '提交成功！',
                  type: 'success',
                })
                this.$emit('submit', 'add')

                if (this.imageId != '') {
                  this.$store.commit('global/setIsReplacePlan', true)
                }
              })
              .catch(() => {
                this.submitLoading = false
                this.$message({
                  message: '提交失败！',
                  type: 'success',
                })
              })
          } else {
            model.files = model.files == '' ? null : model.files
            GridManageApi.updateGird(model)
              .then((ret) => {
                this.submitLoading = false
                this.isVisible = false
                this.$message({
                  message: '修改成功！',
                  type: 'success',
                })
                this.$emit('submit', 'edit')
                if (this.imageId != this.imageId1) {
                  this.$store.commit('global/setIsReplacePlan', true)
                  this.delete2DPoint()
                }
              })
              .catch(() => {
                this.submitLoading = false
                this.$message({
                  message: '修改失败！',
                  type: 'success',
                })
              })
          }
        } else {
          this.$message({
            message: '*必填项不能为空！',
            type: 'warning',
            duration: 4000,
          })
          return false
        }
      })
    },
    getCodeId(list, key) {
      let codeId = ''
      if (this.form[key] && this.form[key] !== '') {
        list.forEach((ele) => {
          if (ele.positionName === this.form[key]) {
            codeId = ele.codeId
          }
        })
      }
      return codeId
    },

    handleSuccess(response, file, fileList) {
      console.log('response=', response)
      console.log('file=', file)
      console.log('fileList=', fileList)
      this.planImgUrl = URL.createObjectURL(file.raw)
      this.imageId = response.uid
      this.$message.success(`图片上传成功！`)
    },
    handleImgError() {
      this.$message.error(`图片上传失败`)
    },
    onConfirmDelete() {
      this.planImgUrl = ''
      this.imageId = ''
      if (this.imageId != this.imageId1) {
        this.$store.commit('global/setIsReplacePlan', true)
      }
    },

    handlePreview(event) {
      console.log('event=', event)
      // this.imgDialogVisible = true
    },
    getImg() {
      GridManageApi.getGridDetail(this.params.item.guid).then((ret) => {
        this.imageId = ret.data.imageId
        this.planImgUrl = ret.data.files ? ret.data.files.url : ''
        this.imageId1 = ret.data.imageId
      })
    },

    delete2DPoint() {
      GridManageApi.getList2DPoint(this.params.item.guid).then((ret) => {
        //  ret.data
        const deviceList = ret.data
        deviceList.forEach((ele) => {
          ele.pointX = 0
          ele.pointY = 0
        })

        GridManageApi.addList2D(deviceList).then((ret) => {
          // this.$message({
          //   message: '保存成功！',
          //   type: 'success',
          // })
        })
      })
    },
  },
}
</script>

<style scoped lang="scss">
@import '../../../../../styles/part-custom';
</style>
